#include "stm32f10x.h"
#include "usart.h"
#include <stdio.h>

void USART1_Init(void)
{

	GPIO_InitTypeDef GPIO_InitStrue;     
    USART_InitTypeDef USART_InitStrue;    
    NVIC_InitTypeDef NVIC_InitStrue;    
	
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1,ENABLE);
    USART_DeInit(USART1);   
 
    GPIO_InitStrue.GPIO_Mode=GPIO_Mode_AF_PP;    
    GPIO_InitStrue.GPIO_Pin=GPIO_Pin_9;   
    GPIO_InitStrue.GPIO_Speed=GPIO_Speed_50MHz;    
    GPIO_Init(GPIOA,&GPIO_InitStrue);
   
    GPIO_InitStrue.GPIO_Mode=GPIO_Mode_IN_FLOATING;   
    GPIO_InitStrue.GPIO_Pin=GPIO_Pin_10;    
    GPIO_Init(GPIOA,&GPIO_InitStrue);
    
    USART_InitStrue.USART_BaudRate=115200;
    USART_InitStrue.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
    USART_InitStrue.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
    USART_InitStrue.USART_Parity=USART_Parity_No;
    USART_InitStrue.USART_StopBits=USART_StopBits_1;    
    USART_InitStrue.USART_WordLength=USART_WordLength_8b;   
    USART_Init(USART1,&USART_InitStrue);   
    
    NVIC_InitStrue.NVIC_IRQChannel=USART1_IRQn; 
    NVIC_InitStrue.NVIC_IRQChannelCmd=ENABLE;    
    NVIC_InitStrue.NVIC_IRQChannelPreemptionPriority=2;
    NVIC_InitStrue.NVIC_IRQChannelSubPriority=1;
    NVIC_Init(&NVIC_InitStrue);    
    
    USART_Cmd(USART1,ENABLE); 
    USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
}

void USART1_IRQHandler(void)        
{
    u16 DATA;
    if(USART_GetITStatus(USART1,USART_IT_RXNE))
    {
    DATA=USART_ReceiveData(USART1);
    USART_SendData(USART1,DATA);
    }
}


#ifdef __GNUC__

int _write(int fd, char *pBuffer, int size)
{
	for (int i = 0; i < size; i++)
	{
		while (!(USART1->SR & USART_SR_TXE));
		USART_SendData(USART1, pBuffer[i]);
	}
	return size;
}
int _read(int fd, char *pBuffer, int size)
{
	for (int i = 0; i < size; i++)
	{
		while ((USART1->SR & USART_SR_RXNE) == 0);
		pBuffer[i] = USART_ReceiveData(USART1);
	}
	return size;
}

#else

int fputc(int ch, FILE *f)
{
	USART_SendData(USART1, (uint8_t)ch);
	while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
	return (ch);
}

int fgetc(FILE *f)
{
	while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
	return (int)USART_ReceiveData(USART1);
}
#endif




